<script>
	import {
		dbInit
	} from 'utils/utils';
	export default {
		onLaunch: function() {
			console.log('App Launch')

			//添加用户登录成功的监听
			let that = this;
			//监听socket状态，如果关闭了，会进行重连
			uni.$on("onSocketOpen", (data) => {
				//保存状态
				uni.setStorageSync("socketstatus", data.status);
				let userid = uni.getStorageSync("login:userid");
				if (!data.status) {
					//监听到关闭，进行重新连接
					uni.connectSocket({
						url: 'ws://localhost:9501/websocket/message/' + userid
					})
					that.buildConn();
				}
			});

			//加载消息等全局分发
			let userId = uni.getStorageSync("login:userid");
			if (userId == null || userId == "") {
				return;
			}
			//重启重连
			this.newConn(userId);


			//初始化数据库
			this.initDb();

			//查询用户信息
			this.getUserInfo(userId);


		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {

			getUserInfo(userId) {

				let that = this;
				//加载用户列表
				uni.request({
					url: "http://localhost:9501/api/userInfo",
					method: 'POST',
					data: {
						userId
					},
					success(res) {
						uni.setStorageSync("login:userinfo", JSON.stringify(res.data.data));
					}
				})

			},

			initDb() {
				dbInit(true);
			},


			newConn(userid) {
				//先关闭上一个连接
				uni.closeSocket({
					
				})
				uni.connectSocket({
					url: 'ws://localhost:9501/websocket/message/' + userid
				})
				uni.setStorageSync("socketstatus", false);
				this.buildConn();
			},

			buildConn() {

				//加载消息
				uni.onSocketMessage(function(res) {
					console.log('收到服务器内容：' + res.data);
					//保存数据到数据库
					uni.$emit("onSocketMessage", res);
				});
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
					//这里才能发送消息
					let val = {
						res: res,
						status: true,
					}
					uni.$emit("onSocketOpen", val); //发送全局事件
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
					let val = {
						res: res,
						status: false,
					}
					uni.$emit("onSocketOpen", val); //发送全局事件
				});
			},




		}
	}
</script>

<style>
	/*每个页面公共css */
</style>